<?php

require_once ("secure_area.php");

class Layby extends Secure_area {

    function __construct() {
        parent::__construct('sales');
        $this->load->library('sale_lib');
        $this->load->model(array('item', 'lay'));
    }

    function index() {
        $this->sale_lib->clear_all();
        $this->_reload();
    }

    function layby_search() {
        $suggestions = $this->lay->get_layby_search_suggestions($this->input->get('term'), 100);
        echo json_encode($suggestions);
    }

    function item_search() {
        $suggestions = $this->Item->get_item_search_suggestions($this->input->get('term'), 100);
        $suggestions = array_merge($suggestions, $this->Item_kit->get_item_kit_search_suggestions($this->input->get('term'), 100));
        echo json_encode($suggestions);
    }

    function customer_search() {
        $suggestions = $this->Customer->get_customer_search_suggestions($this->input->get('term'), 100);
        echo json_encode($suggestions);
    }

    function select_customer() {
        $data = array();
        $customer_id = $this->input->post("customer");
        if ($this->Customer->exists($customer_id)) {
            $this->sale_lib->set_customer($customer_id);
        } else {
            $data['error'] = lang('sales_unable_to_add_customer');
        }
        $this->_reload($data);
    }

    function change_mode() {
        $mode = $this->input->post("mode");
        $this->sale_lib->set_mode($mode);
        $this->_reload();
    }

    function set_comment() {
        $this->sale_lib->set_comment($this->input->post('comment'));
    }

    function set_email_receipt() {
        $this->sale_lib->set_email_receipt($this->input->post('email_receipt'));
    }

    //Alain Multiple Payments
    function add_payment() {
        $data = array();
        $this->form_validation->set_rules('amount_tendered', 'lang:sales_amount_tendered', 'required');

        if ($this->form_validation->run() == FALSE) {
            if ($this->input->post('payment_type') == lang('sales_gift_card'))
                $data['error'] = lang('sales_must_enter_numeric_giftcard');
            else
                $data['error'] = lang('sales_must_enter_numeric');

            $this->_reload($data);
            return;
        }

        $payment_type = $this->input->post('payment_type');
        if ($payment_type == lang('sales_giftcard')) {
            if (!$this->Giftcard->exists($this->Giftcard->get_giftcard_id($this->input->post('amount_tendered')))) {
                $data['error'] = lang('sales_giftcard_does_not_exist');
                $this->_reload($data);
                return;
            }

            $payments = $this->sale_lib->get_payments();
            $payment_type = $this->input->post('payment_type') . ':' . $this->input->post('amount_tendered');
            $current_payments_with_giftcard = isset($payments[$payment_type]) ? $payments[$payment_type]['payment_amount'] : 0;
            $cur_giftcard_value = $this->Giftcard->get_giftcard_value($this->input->post('amount_tendered')) - $current_payments_with_giftcard;
            if ($cur_giftcard_value <= 0 && $this->sale_lib->get_total() > 0) {
                $data['error'] = lang('sales_giftcard_balance_is') . ' ' . to_currency($this->Giftcard->get_giftcard_value($this->input->post('amount_tendered'))) . ' !';
                $this->_reload($data);
                return;
            } elseif (( $this->Giftcard->get_giftcard_value($this->input->post('amount_tendered')) - $this->sale_lib->get_total() ) > 0) {
                $data['warning'] = lang('sales_giftcard_balance_is') . ' ' . to_currency($this->Giftcard->get_giftcard_value($this->input->post('amount_tendered')) - $this->sale_lib->get_total()) . ' !';
            }
            $payment_amount = min($this->sale_lib->get_amount_due(), $this->Giftcard->get_giftcard_value($this->input->post('amount_tendered')));
        } else {
            $payment_amount = $this->input->post('amount_tendered');
        }

        if (!$this->sale_lib->add_payment($payment_type, $payment_amount)) {
            $data['error'] = lang('sales_unable_to_add_payment');
        }

        $this->_reload($data);
    }

    //Alain Multiple Payments
    function delete_payment($payment_id) {
        $this->sale_lib->delete_payment(urldecode($payment_id));
        $this->_reload();
    }

    function search() {
        $this->sale_lib->clear_all();
        $data = array();
        $data['sale_id'] = $this->input->post("item");
        $this->sale_lib->set_layby_search($data['sale_id']);
        $data['layby_search'] = 1;
        $this->_reload($data);
    }

    function add() {
        $data = array();
        $mode = $this->sale_lib->get_mode();
        $this->sale_lib->empty_layby_search();
        $item_id_or_number_or_item_kit_or_receipt = $this->input->post("item");
        $quantity = $mode == "sale" ? 1 : -1;

        if ($this->sale_lib->is_valid_receipt($item_id_or_number_or_item_kit_or_receipt) && $mode == 'return') {
            $this->sale_lib->return_entire_sale($item_id_or_number_or_item_kit_or_receipt);
        } elseif ($this->sale_lib->is_valid_item_kit($item_id_or_number_or_item_kit_or_receipt)) {
            $this->sale_lib->add_item_kit($item_id_or_number_or_item_kit_or_receipt, $quantity);
        } else {

            $add_item = $this->sale_lib->add_item($item_id_or_number_or_item_kit_or_receipt, $quantity);
            if ($add_item != "true") {
                $data['error'] = lang('sales_unable_to_add_item');
            } else {
                $list_make_receipt = $this->session->userdata('list_make_receipt');
                $t_item_info = $this->Item->get_info($item_id_or_number_or_item_kit_or_receipt);
                $item_info = array(
                    'name' => $t_item_info->name,
                    'cost' => $t_item_info->unit_price,
                    'item_id' => $t_item_info->item_id,
                    'quantity' => $quantity
                );
                if (!empty($list_make_receipt)) {
                    $this->Service->insert_order($item_info, $list_make_receipt);
                }
            }
        }

        if ($this->sale_lib->out_of_stock($item_id_or_number_or_item_kit_or_receipt)) {
            $data['warning'] = lang('sales_quantity_less_than_zero');
        }
        $this->_reload($data);
    }

    function edit_item($line) {
        $data = array();

        $this->form_validation->set_rules('price', 'lang:items_price', 'required|numeric');
        $this->form_validation->set_rules('quantity', 'lang:items_quantity', 'required|numeric');

        $description = $this->input->post("description");
        $serialnumber = $this->input->post("serialnumber");
        $price = $this->input->post("price");
        $quantity = $this->input->post("quantity");
        $discount = $this->input->post("discount");


        if ($this->form_validation->run() != FALSE) {
            $this->sale_lib->edit_item($line, $description, $serialnumber, $quantity, $discount, $price);
        } else {
            $data['error'] = lang('sales_error_editing_item');
        }

        if ($this->sale_lib->out_of_stock($this->sale_lib->get_item_id($line))) {
            $data['warning'] = lang('sales_quantity_less_than_zero');
        }


        $this->_reload($data);
    }

    function delete_item($item_number) {
        $this->sale_lib->delete_item($item_number);
        $this->_reload();
    }

    function delete_customer() {
        $this->sale_lib->delete_customer();
        $this->_reload();
    }

    function complete() {
        $data = array();
        $data['layby_sale_id'] = $this->sale_lib->get_layby_search();
        if (isset($data['layby_sale_id']) && $data['layby_sale_id'] > 0) {
            $data['cart'] = $this->lay->get_sale_items($data['layby_sale_id'])->result_array();
            for ($index = 0; $index < count($data['cart']); $index++) {
                $data['cart'][$index]['quantity'] = $data['cart'][$index]['quantity_purchased'];
                $data['cart'][$index]['discount'] = $data['cart'][$index]['discount_percent'];
                $data['cart'][$index]['price'] = $data['cart'][$index]['item_unit_price'];
            }
            $data['items_in_cart'] = $this->lay->get_items_in_cart($data['layby_sale_id']);
            $data['subtotal'] = $this->lay->get_subtotal($data['layby_sale_id']);
            $data['total'] = $this->lay->get_total($data['layby_sale_id']);
            $data['taxes'] = $this->lay->get_taxes($data['layby_sale_id']);
            $data['layby_search'] = 1;
            $data['balance'] = $this->lay->get_balance($data['layby_sale_id']);
            $data['amount_due'] = $data['balance'];
            $data['balance'] = $data['balance'] - ($this->sale_lib->get_amount_due() * -1);
            $data['amount_due_sess'] = $this->sale_lib->get_amount_due();
            if (abs($data['amount_due_sess']) > 0) {
                $data['amount_due'] -= ($data['amount_due_sess'] * -1);
            }
            $customer_id = $this->lay->get_customer_id($data['layby_sale_id']);
            $comment = $this->lay->get_comment();
        } else {
            $data['cart'] = $this->sale_lib->get_cart();
            $data['subtotal'] = $this->sale_lib->get_subtotal();
            $customer_id = $this->sale_lib->get_customer();
            $data['taxes'] = $this->sale_lib->get_taxes();
            $data['total'] = $this->sale_lib->get_total();
            $data['balance'] = $this->sale_lib->get_amount_due();
            $comment = $this->sale_lib->get_comment();
            $data['amount_change'] = to_currency($this->sale_lib->get_amount_due() * -1);
        }
        //$data['cart'] = $this->sale_lib->get_cart();
        //$data['subtotal'] = $this->sale_lib->get_subtotal();
        //$data['taxes'] = $this->sale_lib->get_taxes();
        //$data['total'] = $this->sale_lib->get_total();
        $data['receipt_title'] = ($data['balance'] == 0 ? lang('sale_tax_receipt') : lang('layby_receipt'));
        $data['layby_print'] = ($data['balance'] == 0 ? lang('layby_print_invoice') : lang('layby_print_receipt'));
        $data['transaction_time'] = date(get_date_format() . ' ' . get_time_format());
        //$customer_id = $this->sale_lib->get_customer();
        $employee_id = $this->Employee->get_logged_in_employee_info()->person_id;
        //$comment = $this->sale_lib->get_comment();
        $emp_info = $this->Employee->get_info($employee_id);
        $data['payments'] = $this->sale_lib->get_payments();
        $data['deposit'] = $this->sale_lib->get_payments_total();
        //$data['amount_change'] = to_currency($this->sale_lib->get_amount_due() * -1);
        //$data['balance'] = $this->sale_lib->get_amount_due() * -1;
        $data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

        if ($customer_id != -1 or !is_null($customer_id)) {
            $cust_info = $this->Customer->get_info($customer_id);
            $data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name . ($cust_info->company_name == '' ? '' : ' (' . $cust_info->company_name . ')');
            $data['customer_address'] = $cust_info->address_1;
            $data['customer_suburd'] = $cust_info->suburd;
            $data['customer_state'] = $cust_info->state;
            $data['customer_postcode'] = $cust_info->zip;
            $data['customer_phone'] = $cust_info->phone_number;
        }

        //SAVE sale to database
        if (isset($data['layby_sale_id']) && $data['layby_sale_id'] > 0) {
            if ($this->sale_lib->get_email_receipt() && !empty($cust_info->email)) {
                $this->load->library('email');
                $config['mailtype'] = 'html';
                $this->email->initialize($config);
                $this->email->from($this->config->item('email'), $this->config->item('company'));
                $this->email->to($cust_info->email);

                $this->email->subject(lang('sales_receipt'));
                $this->email->message($this->load->view("sales/receipt_email", $data, true));
                $this->email->send();
            }
            $layby = array(
                'sale_id' => $data['layby_sale_id'],
                'deposit' => $data['deposit'],
                'balance' => $data['balance'],
                'pickup' => date('Y-m-d', strtotime($this->input->post('pickup')))
            );
            $this->lay->save($layby);
            $data['deposits'] = $this->lay->get_deposit_list($data['layby_sale_id']);
        } else {
            $data['sale_id'] = $this->Sale->save($data['cart'], $customer_id, $employee_id, $comment, $data['payments']);
            if ($data['sale_id'] == '-1') {
                $data['error_message'] = lang('sales_transaction_failed');
            } else {
                if ($this->sale_lib->get_email_receipt() && !empty($cust_info->email)) {
                    $this->load->library('email');
                    $config['mailtype'] = 'html';
                    $this->email->initialize($config);
                    $this->email->from($this->config->item('email'), $this->config->item('company'));
                    $this->email->to($cust_info->email);

                    $this->email->subject(lang('sales_receipt'));
                    $this->email->message($this->load->view("sales/receipt_email", $data, true));
                    $this->email->send();
                }
                $layby = array(
                    'sale_id' => $data['sale_id'],
                    'deposit' => $data['deposit'],
                    'balance' => $data['balance'],
                    'pickup' => date('Y-m-d', strtotime($this->input->post('pickup')))
                );
                $this->lay->save($layby);
                $data['deposits'] = $this->lay->get_deposit_list($data['sale_id']);
            }
        }

        $this->load->view("layby/receipt", $data);
        $this->sale_lib->clear_all();
    }

    function docomplete() {
        $data = array();
        $data['layby_sale_id'] = $this->sale_lib->get_layby_search();
        if (isset($data['layby_sale_id']) && $data['layby_sale_id'] > 0) {
            $data['cart'] = $this->lay->get_sale_items($data['layby_sale_id'])->result_array();
            for ($index = 0; $index < count($data['cart']); $index++) {
                $data['cart'][$index]['quantity'] = $data['cart'][$index]['quantity_purchased'];
                $data['cart'][$index]['discount'] = $data['cart'][$index]['discount_percent'];
                $data['cart'][$index]['price'] = $data['cart'][$index]['item_unit_price'];
            }
            $data['items_in_cart'] = $this->lay->get_items_in_cart($data['layby_sale_id']);
            $data['subtotal'] = $this->lay->get_subtotal($data['layby_sale_id']);
            $data['total'] = $this->lay->get_total($data['layby_sale_id']);
            $data['taxes'] = $this->lay->get_taxes($data['layby_sale_id']);
            $data['layby_search'] = 1;
            $data['balance'] = $this->lay->get_balance($data['layby_sale_id']);
            $data['amount_due'] = $data['balance'];
            $data['balance'] = $data['balance'] - ($this->sale_lib->get_amount_due() * -1);
            $data['amount_due_sess'] = $this->sale_lib->get_amount_due();
            if (abs($data['amount_due_sess']) > 0) {
                $data['amount_due'] -= ($data['amount_due_sess'] * -1);
            }
            $customer_id = $this->lay->get_customer_id($data['layby_sale_id']);
            $comment = $this->lay->get_comment();
        } else {
            $data['cart'] = $this->sale_lib->get_cart();
            $data['subtotal'] = $this->sale_lib->get_subtotal();
            $customer_id = $this->sale_lib->get_customer();
            $data['taxes'] = $this->sale_lib->get_taxes();
            $data['total'] = $this->sale_lib->get_total();
            $data['balance'] = $this->sale_lib->get_amount_due() * -1;
            $comment = $this->sale_lib->get_comment();
            $data['amount_change'] = to_currency($this->sale_lib->get_amount_due() * -1);
        }
        //$data['cart'] = $this->sale_lib->get_cart();
        //$data['subtotal'] = $this->sale_lib->get_subtotal();
        //$data['taxes'] = $this->sale_lib->get_taxes();
        //$data['total'] = $this->sale_lib->get_total();
        $data['receipt_title'] = lang('layby_receipt');
        $data['transaction_time'] = date(get_date_format() . ' ' . get_time_format());
        //$customer_id = $this->sale_lib->get_customer();
        $employee_id = $this->Employee->get_logged_in_employee_info()->person_id;
        //$comment = $this->sale_lib->get_comment();
        $emp_info = $this->Employee->get_info($employee_id);
        $data['payments'] = $this->sale_lib->get_payments();
        $data['deposit'] = $this->sale_lib->get_payments_total();
        //$data['amount_change'] = to_currency($this->sale_lib->get_amount_due() * -1);
        //$data['balance'] = $this->sale_lib->get_amount_due() * -1;
        $data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

        if ($customer_id != -1 or !is_null($customer_id)) {
            $cust_info = $this->Customer->get_info($customer_id);
            $data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name . ($cust_info->company_name == '' ? '' : ' (' . $cust_info->company_name . ')');
            $data['customer_address'] = $cust_info->address_1;
            $data['customer_suburd'] = $cust_info->suburd;
            $data['customer_state'] = $cust_info->state;
            $data['customer_postcode'] = $cust_info->zip;
            $data['customer_phone'] = $cust_info->phone_number;
        }

        //SAVE sale to database
        if (isset($data['layby_sale_id']) && $data['layby_sale_id'] > 0) {
            if ($this->sale_lib->get_email_receipt() && !empty($cust_info->email)) {
                $this->load->library('email');
                $config['mailtype'] = 'html';
                $this->email->initialize($config);
                $this->email->from($this->config->item('email'), $this->config->item('company'));
                $this->email->to($cust_info->email);

                $this->email->subject(lang('sales_receipt'));
                $this->email->message($this->load->view("sales/receipt_email", $data, true));
                $this->email->send();
            }
            $layby = array(
                'sale_id' => $data['layby_sale_id'],
                'deposit' => $data['deposit'],
                'balance' => $data['balance'],
                'pickup' => date('Y-m-d', strtotime($this->input->post('pickup')))
            );
            $this->lay->save($layby);
            $data['deposits'] = $this->lay->get_deposit_list($data['layby_sale_id']);
        } else {
            $data['sale_id'] = $this->Sale->save($data['cart'], $customer_id, $employee_id, $comment, $data['payments']);
            if ($data['sale_id'] == '-1') {
                $data['error_message'] = lang('sales_transaction_failed');
            } else {
                if ($this->sale_lib->get_email_receipt() && !empty($cust_info->email)) {
                    $this->load->library('email');
                    $config['mailtype'] = 'html';
                    $this->email->initialize($config);
                    $this->email->from($this->config->item('email'), $this->config->item('company'));
                    $this->email->to($cust_info->email);

                    $this->email->subject(lang('sales_receipt'));
                    $this->email->message($this->load->view("sales/receipt_email", $data, true));
                    $this->email->send();
                }
                $layby = array(
                    'sale_id' => $data['sale_id'],
                    'deposit' => $data['deposit'],
                    'balance' => $data['balance'],
                    'pickup' => date('Y-m-d', strtotime($this->input->post('pickup')))
                );
                $this->lay->save($layby);
                $data['deposits'] = $this->lay->get_deposit_list($data['sale_id']);
            }
        }
        $this->load->view("layby/receipt", $data);
        $this->sale_lib->clear_all();
    }

    function email_receipt($sale_id) {
        $sale_info = $this->Sale->get_info($sale_id)->row_array();
        $this->sale_lib->copy_entire_sale($sale_id);
        $data['cart'] = $this->sale_lib->get_cart();
        $data['payments'] = $this->sale_lib->get_payments();
        $data['subtotal'] = $this->sale_lib->get_subtotal();
        $data['taxes'] = $this->sale_lib->get_taxes($sale_id);
        $data['total'] = $this->sale_lib->get_total($sale_id);
        $data['receipt_title'] = lang('sales_receipt');
        $data['transaction_time'] = date(get_date_format() . ' ' . get_time_format(), strtotime($sale_info['sale_time']));
        $customer_id = $this->sale_lib->get_customer();
        $emp_info = $this->Employee->get_info($sale_info['employee_id']);
        $data['payment_type'] = $sale_info['payment_type'];
        $data['amount_change'] = to_currency($this->sale_lib->get_amount_due($sale_id) * -1);
        $data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

        if ($customer_id != -1) {
            $cust_info = $this->Customer->get_info($customer_id);
            $data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name . ($cust_info->company_name == '' ? '' : ' (' . $cust_info->company_name . ')');
        }
        $data['sale_id'] = 'POS ' . $sale_id;
        if (!empty($cust_info->email)) {
            $this->load->library('email');
            $config['mailtype'] = 'html';
            $this->email->initialize($config);
            $this->email->from($this->config->item('email'), $this->config->item('company'));
            $this->email->to($cust_info->email);

            $this->email->subject(lang('sales_receipt'));
            $this->email->message($this->load->view("sales/receipt_email", $data, true));
            $this->email->send();
        }

        $this->sale_lib->clear_all();
    }

    function receipt($sale_id) {
        $sale_info = $this->Sale->get_info($sale_id)->row_array();
        $this->sale_lib->copy_entire_sale($sale_id);
        $data['cart'] = $this->sale_lib->get_cart();
        $data['payments'] = $this->sale_lib->get_payments();
        $data['subtotal'] = $this->sale_lib->get_subtotal();
        $data['taxes'] = $this->sale_lib->get_taxes($sale_id);
        $data['total'] = $this->sale_lib->get_total($sale_id);
        $data['receipt_title'] = lang('sales_receipt');
        $data['transaction_time'] = date(get_date_format() . ' ' . get_time_format(), strtotime($sale_info['sale_time']));
        $customer_id = $this->sale_lib->get_customer();
        $emp_info = $this->Employee->get_info($sale_info['employee_id']);
        $data['payment_type'] = $sale_info['payment_type'];
        $data['amount_change'] = to_currency($this->sale_lib->get_amount_due($sale_id) * -1);
        $data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

        if ($customer_id != -1) {
            $cust_info = $this->Customer->get_info($customer_id);
            $data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name . ($cust_info->company_name == '' ? '' : ' (' . $cust_info->company_name . ')');
        }
        $data['sale_id'] = 'POS ' . $sale_id;
        $this->load->view("sales/receipt", $data);
        $this->sale_lib->clear_all();
    }

    function doreceipt($sale_id) {
        $sale_info = $this->Sale->get_info($sale_id)->row_array();
        $this->sale_lib->copy_entire_sale($sale_id);
        $data['cart'] = $this->sale_lib->get_cart();
        $data['payments'] = $this->sale_lib->get_payments();
        $data['subtotal'] = $this->sale_lib->get_subtotal();
        $data['taxes'] = $this->sale_lib->get_taxes($sale_id);
        $data['total'] = $this->sale_lib->get_total($sale_id);
        $data['receipt_title'] = lang('sales_receipt');
        $data['transaction_time'] = date(get_date_format() . ' ' . get_time_format(), strtotime($sale_info['sale_time']));
        $customer_id = $this->sale_lib->get_customer();
        $emp_info = $this->Employee->get_info($sale_info['employee_id']);
        $data['payment_type'] = $sale_info['payment_type'];
        $data['amount_change'] = to_currency($this->sale_lib->get_amount_due($sale_id) * -1);
        $data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

        if ($customer_id != -1) {
            $cust_info = $this->Customer->get_info($customer_id);
            $data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name . ($cust_info->company_name == '' ? '' : ' (' . $cust_info->company_name . ')');
        }
        $data['sale_id'] = 'POS ' . $sale_id;
        $this->load->view("sales/doreceipt", $data);
        $this->sale_lib->clear_all();
    }

    function edit($sale_id) {
        $data = array();

        $data['customers'] = array('' => 'No Customer');
        foreach ($this->Customer->get_all()->result() as $customer) {
            $data['customers'][$customer->person_id] = $customer->first_name . ' ' . $customer->last_name;
        }

        $data['employees'] = array();
        foreach ($this->Employee->get_all()->result() as $employee) {
            $data['employees'][$employee->person_id] = $employee->first_name . ' ' . $employee->last_name;
        }

        $data['sale_info'] = $this->Sale->get_info($sale_id)->row_array();


        $this->load->view('sales/edit', $data);
    }

    function delete($sale_id) {
        $data = array();

        if ($this->Sale->delete($sale_id)) {
            $data['success'] = true;
        } else {
            $data['success'] = false;
        }

        $this->load->view('sales/delete', $data);
    }

    function undelete($sale_id) {
        $data = array();

        if ($this->Sale->undelete($sale_id)) {
            $data['success'] = true;
        } else {
            $data['success'] = false;
        }

        $this->load->view('sales/undelete', $data);
    }

    function save($sale_id) {
        $sale_data = array(
            'sale_time' => date('Y-m-d', strtotime($this->input->post('date'))),
            'customer_id' => $this->input->post('customer_id') ? $this->input->post('customer_id') : null,
            'employee_id' => $this->input->post('employee_id'),
            'comment' => $this->input->post('comment')
        );

        if ($this->Sale->update($sale_data, $sale_id)) {
            echo json_encode(array('success' => true, 'message' => lang('sales_successfully_updated')));
        } else {
            echo json_encode(array('success' => false, 'message' => lang('sales_unsuccessfully_updated')));
        }
    }

    function _payments_cover_total() {
        $total_payments = 0;

        foreach ($this->sale_lib->get_payments() as $payment) {
            $total_payments += $payment['payment_amount'];
        }

        /* Changed the conditional to account for floating point rounding */
        if (( $this->sale_lib->get_mode() == 'sale' ) && ( ( to_currency_no_money($this->sale_lib->get_total()) - $total_payments ) > 1e-6 )) {
            return false;
        }

        return true;
    }

    function _reload($data = array()) {
        $data['sale_id'] = $this->sale_lib->get_layby_search();
        if (isset($data['sale_id']) && $data['sale_id'] > 0) {
            $data['cart'] = $this->lay->get_sale_items($data['sale_id'])->result_array();
            for ($index = 0; $index < count($data['cart']); $index++) {
                $data['cart'][$index]['quantity'] = $data['cart'][$index]['quantity_purchased'];
                $data['cart'][$index]['discount'] = $data['cart'][$index]['discount_percent'];
                $data['cart'][$index]['price'] = $data['cart'][$index]['item_unit_price'];
            }
            $data['items_in_cart'] = $this->lay->get_items_in_cart($data['sale_id']);
            $data['subtotal'] = $this->lay->get_subtotal($data['sale_id']);
            $data['total'] = $this->lay->get_total($data['sale_id']);
            $data['taxes'] = $this->lay->get_taxes($data['sale_id']);
            //$data['amount_due'] = $this->lay->get_amount_due($data['sale_id']);
            $data['balance'] = $this->lay->get_balance($data['sale_id']);
            $data['layby_last'] = $this->lay->get_layby_last($data['sale_id']);
            $data['expr'] = false;
            $expr = strtotime(date('d-m-Y 23:59:59', strtotime($data['layby_last']->pickup)));
            $data['pickup'] = date('d-m-Y',$expr);
            $now = time();
            if ($now < $expr) {
                $data['expr'] = true;
            }
            $data['amount_due'] = $data['balance'];
            $data['amount_due_sess'] = $this->sale_lib->get_amount_due() * -1;
            if (abs($data['amount_due_sess']) > 0) {
                $data['amount_due'] = $data['amount_due'] - ($data['amount_due_sess']);
            }
        } else {
            $data['expr'] = true;
            $data['cart'] = $this->sale_lib->get_cart();
            $data['items_in_cart'] = $this->sale_lib->get_items_in_cart();
            $data['subtotal'] = $this->sale_lib->get_subtotal();
            $data['total'] = $this->sale_lib->get_total();
            $data['taxes'] = $this->sale_lib->get_taxes();
            $data['amount_due'] = $this->sale_lib->get_amount_due();
        }
        $person_info = $this->Employee->get_logged_in_employee_info();
        //$data['cart'] = $this->sale_lib->get_cart();
        $data['modes'] = array('sale' => lang('sales_sale'), 'return' => lang('sales_return'));
        $data['mode'] = $this->sale_lib->get_mode();
        //$data['items_in_cart'] = $this->sale_lib->get_items_in_cart();
        //$data['subtotal'] = $this->sale_lib->get_subtotal();
        //$data['taxes'] = $this->sale_lib->get_taxes();
        //$data['total'] = $this->sale_lib->get_total();
        $data['items_module_allowed'] = $this->Employee->has_permission('items', $person_info->person_id);
        $data['comment'] = $this->sale_lib->get_comment();
        $data['email_receipt'] = $this->sale_lib->get_email_receipt();
        $data['payments_total'] = $this->sale_lib->get_payments_total();
        //$data['amount_due'] = $this->sale_lib->get_amount_due();
        $data['payments'] = $this->sale_lib->get_payments();
        //------------------------------------------------------------------------------              
        //get payment method
        $payments = $this->Payments->get_all();
        foreach ($payments->result() as $payment) {
            $data['payment_options'][$payment->name] = $payment->name;
        }
        //end get payment method --------------------------------------------------------

        $data['username'] = $person_info->username;
        $data['discount'] = $person_info->discount;
        $customer_id = $this->sale_lib->get_customer();
        if ($customer_id != -1) {
            $info = $this->Customer->get_info($customer_id);
            $data['customer'] = $info->first_name . ' ' . $info->last_name . ($info->company_name == '' ? '' : ' (' . $info->company_name . ')');
            $data['customer_email'] = $info->email;
            $data['customer_id'] = $customer_id;
        }
        $data['payments_cover_total'] = $this->_payments_cover_total();
        $this->load->view("layby/register", $data);
    }

    function cancel_sale() {
        $this->sale_lib->clear_all();
        $this->_reload();
    }

    function suspend() {
        $data['cart'] = $this->sale_lib->get_cart();
        $data['subtotal'] = $this->sale_lib->get_subtotal();
        $data['taxes'] = $this->sale_lib->get_taxes();
        $data['total'] = $this->sale_lib->get_total();
        $data['receipt_title'] = lang('sales_receipt');
        $data['transaction_time'] = date(get_date_format() . ' ' . get_time_format());
        $customer_id = $this->sale_lib->get_customer();
        $employee_id = $this->Employee->get_logged_in_employee_info()->person_id;
        $comment = $this->sale_lib->get_comment();
        $emp_info = $this->Employee->get_info($employee_id);
        //Alain Multiple payments
        $data['payments'] = $this->sale_lib->get_payments();
        $data['amount_change'] = to_currency($this->sale_lib->get_amount_due() * -1);
        $data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

        if ($customer_id != -1) {
            $cust_info = $this->Customer->get_info($customer_id);
            $data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name . ($cust_info->company_name == '' ? '' : ' (' . $cust_info->company_name . ')');
        }

        $total_payments = 0;

        foreach ($data['payments'] as $payment) {
            $total_payments += $payment['payment_amount'];
        }

        $sale_id = $this->sale_lib->get_suspended_sale_id();
        //SAVE sale to database
        $data['sale_id'] = 'POS ' . $this->Sale_suspended->save($data['cart'], $customer_id, $employee_id, $comment, $data['payments'], $sale_id);
        if ($data['sale_id'] == 'POS -1') {
            $data['error_message'] = lang('sales_transaction_failed');
        }
        $this->sale_lib->clear_all();
        $this->_reload(array('success' => lang('sales_successfully_suspended_sale')));
    }

    function suspended() {
        $data = array();
        $data['suspended_sales'] = $this->Sale_suspended->get_all()->result_array();
        $this->load->view('sales/suspended', $data);
    }

    function unsuspend() {
        $sale_id = $this->input->post('suspended_sale_id');
        $this->sale_lib->clear_all();
        $this->sale_lib->copy_entire_suspended_sale($sale_id);
        $this->sale_lib->set_suspended_sale_id($sale_id);
        $this->Sale_suspended->delete($sale_id);
        $this->_reload();
    }

}

?>